package com.hjm.project.GoodsInfo.GoodsInfo.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.DateUtils;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.framework.config.CustomConfig;
import com.hjm.project.BusinessInfo.BusinessInfo.domain.BusinessInfo;
import com.hjm.project.BusinessInfo.BusinessInfo.mapper.BusinessInfoMapper;
import com.hjm.project.agentInfo.agentInfo.utils.Utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;
import com.hjm.project.GoodsInfo.GoodsInfo.mapper.GoodsInfoMapper;
import com.hjm.project.GoodsInfo.GoodsInfo.domain.GoodsInfo;
import com.hjm.project.GoodsInfo.GoodsInfo.service.IGoodsInfoService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 商品Service业务层处理
 * 
 * @author GoodsInfo
 * @date 2020-11-30
 */
@Service
public class GoodsInfoServiceImpl implements IGoodsInfoService 
{
    @Resource
    private GoodsInfoMapper goodsInfoMapper;

    @Resource
    private BusinessInfoMapper businessInfoMapper; //图片

    /**
     * 查询商品
     * 
     * @param id 商品ID
     * @return 商品
     */
    @Override
    public GoodsInfo selectGoodsInfoById(Long id) {
        return goodsInfoMapper.selectGoodsInfoById(id);
    }

    /**
     * 查询商品列表
     * 
     * @param goodsInfo 商品
     * @return 商品
     */
    @Override
    public List<GoodsInfo> selectGoodsInfoList(GoodsInfo goodsInfo)
    {
        return goodsInfoMapper.selectGoodsInfoList(goodsInfo);
    }

    /**
     * 新增商品
     * 
     * @param goodsInfo 商品
     * @return 结果
     */
    @Override
    public int insertGoodsInfo(GoodsInfo goodsInfo)
    {
        goodsInfo.setCreateTime(DateUtils.getNowDate());
        return goodsInfoMapper.insertGoodsInfo(goodsInfo);
    }
    @Transactional
    @Override
    public int insertGoodsInfos(GoodsInfo goodsInfo, MultipartFile home, List<MultipartFile> detailImg, List<MultipartFile> lbImg, List<MultipartFile> hdImg, Map<String, MultipartFile> updateImg) throws IOException {
        try {
            goodsInfo.setCreateTime(DateUtils.getNowDate());
            /***********************开始上传图片******************************/

            //存在ID添加 反之 更新
            if (goodsInfo.getId() == null) {
                goodsInfo.setGdNumber(com.hjm.project.GoodsInfo.GoodsInfo.utils.Utils.getSerialNo());
                 goodsInfoMapper.insertGoodsInfo(goodsInfo);
            } else {
                //首页图只保留一个
                BusinessInfo businessInfo = new BusinessInfo();
                businessInfo.setType(Long.parseLong("1"));
                businessInfo.setPicId(goodsInfo.getId());
                List<BusinessInfo> businessInfos = businessInfoMapper.selectBusinessInfoList(businessInfo);
                //存在图片名称 并且 库中图片记录存在 说明是修改
                if (StringUtils.isNotEmpty(home.getOriginalFilename()) && CollectionUtils.isNotEmpty(businessInfos)) {
                    int i = businessInfoMapper.deleteBusinessInfoByName(businessInfo);
                    if (i > 0) {
                        for (BusinessInfo info : businessInfos) {
                            FastDFSClient.deleteFile(info.getUrl());
                        }
                    }

                }

                goodsInfoMapper.updateGoodsInfo(goodsInfo);
            }

            /**
             * 首页图片
             **/
            BusinessInfo businessInfo = new BusinessInfo();
            String pid = uploadImg(home);
            if (StringUtils.isNotEmpty(pid)) {
                //获取商品的主键
                businessInfo = new BusinessInfo();
                businessInfo.setPicId(goodsInfo.getId());
                businessInfo.setDescribe("商品首页");
                businessInfo.setUrl(pid);
                businessInfo.setType(Long.parseLong("1"));
                businessInfo.setStatus(Long.parseLong("1"));
                businessInfo.setProType(Long.parseLong("1"));
                businessInfo.setCreateTime(DateUtils.getDateTime());
                businessInfo.setUpdateTime(DateUtils.getDateTime());
                businessInfoMapper.insertBusinessInfo(businessInfo);
            }

            /**
             * 轮播图
             **/
            for (MultipartFile lb : lbImg) {
                //上传
                pid = uploadImg(lb);
                if (StringUtils.isNotEmpty(pid)) {
                    businessInfo = new BusinessInfo();
                    businessInfo.setPicId(goodsInfo.getId());
                    businessInfo.setDescribe("轮播图");
                    businessInfo.setUrl(pid);
                    businessInfo.setType(Long.parseLong("2"));
                    businessInfo.setStatus(Long.parseLong("1"));
                    businessInfo.setProType(Long.parseLong("1"));
                    businessInfo.setCreateTime(DateUtils.getDateTime());
                    businessInfo.setUpdateTime(DateUtils.getDateTime());
                    businessInfoMapper.insertBusinessInfo(businessInfo);
                }
            }

            /**
             * 详情图
             **/
            for (MultipartFile dimg : detailImg) {
                //上传
                pid = uploadImg(dimg);
                if (StringUtils.isNotEmpty(pid)) {
                    businessInfo = new BusinessInfo();
                    businessInfo.setPicId(goodsInfo.getId());
                    businessInfo.setDescribe("详情图");
                    businessInfo.setUrl(pid);
                    businessInfo.setType(Long.parseLong("3"));
                    businessInfo.setStatus(Long.parseLong("1"));
                    businessInfo.setProType(Long.parseLong("1"));
                    businessInfo.setCreateTime(DateUtils.getDateTime());
                    businessInfo.setUpdateTime(DateUtils.getDateTime());
                    businessInfoMapper.insertBusinessInfo(businessInfo);
                }
            }
            /**
             * 活动图
             **/
            for (MultipartFile hd : hdImg) {
                //上传
                pid = uploadImg(hd);
                if (StringUtils.isNotEmpty(pid)) {
                    businessInfo = new BusinessInfo();
                    businessInfo.setPicId(goodsInfo.getId());
                    businessInfo.setDescribe("活动图");
                    businessInfo.setUrl(pid);
                    businessInfo.setType(Long.parseLong("11"));
                    businessInfo.setStatus(Long.parseLong("1"));
                    businessInfo.setProType(Long.parseLong("1"));
                    businessInfo.setCreateTime(DateUtils.getDateTime());
                    businessInfo.setUpdateTime(DateUtils.getDateTime());
                    businessInfoMapper.insertBusinessInfo(businessInfo);
                }
            }
            for (String imgId : updateImg.keySet()) {
                if (Utils.isNumber(imgId)){
                    MultipartFile file = updateImg.get(imgId);
                    pid = uploadImg(file);
                    if (StringUtils.isNotEmpty(pid)) {
                        businessInfo = new BusinessInfo();
                        businessInfo.setId(Long.parseLong(imgId));
                        businessInfo.setUrl(pid);
                        businessInfo.setUpdateTime(DateUtils.getDateTime());
                        businessInfoMapper.updateBusinessInfo(businessInfo);
                    }
                }
            }


        }catch (Exception e){
            e.printStackTrace();
            throw  new BusinessException("上传图片失败");
        }
        return 1;
    }


    @Transactional
    @Override
    public int updateGoodsInfo(GoodsInfo goodsInfo, MultipartFile home, List<MultipartFile>dImg, List<MultipartFile> lbImg) throws IOException {
        try {
            goodsInfo.setCreateTime(DateUtils.getNowDate());
            /***********************开始更新商品信息******************************/
                goodsInfoMapper.updateGoodsInfo(goodsInfo);
                //获取商品的所有图片
                BusinessInfo business = new BusinessInfo();
                business.setPicId(goodsInfo.getId());
                List<BusinessInfo> businessInfos = businessInfoMapper.selectBusinessInfoList(business);
                //如果获取到的图片name为空那么视为新增 旧图不做操作
                if (CollectionUtils.isNotEmpty(businessInfos)) {
                    List<String> ids = new ArrayList<>();
                    for (BusinessInfo info : businessInfos) {
                        ids.add(info.getId().toString());
                        //删除图片服务器的地址
                        FastDFSClient.deleteFile(info.getUrl());
                    }
                    //批量删除数据库中的图片地址
                    businessInfoMapper.deleteBusinessInfoByIds(ids.toArray(new String[ids.size()]));
                }

            /**
             * 首页图片
             **/
            String pid = uploadImg(home);
            //获取商品的主键
            BusinessInfo businessInfo = new BusinessInfo();
            businessInfo = new BusinessInfo();
            businessInfo.setPicId(goodsInfo.getId());
            businessInfo.setDescribe("商品首页");
            businessInfo.setUrl(pid);
            businessInfo.setType(Long.parseLong("1"));
            businessInfo.setStatus(Long.parseLong("1"));
            businessInfo.setProType(Long.parseLong("1"));
            businessInfo.setCreateTime(DateUtils.getDateTime());
            businessInfo.setUpdateTime(DateUtils.getDateTime());
            businessInfoMapper.insertBusinessInfo(businessInfo);

            /**
             * 详情图
             **/
            for (MultipartFile dimg : dImg) {
                //上传
                pid = uploadImg(dimg);
                businessInfo = new BusinessInfo();
                businessInfo.setPicId(goodsInfo.getId());
                businessInfo.setDescribe("详情图");
                businessInfo.setUrl(pid);
                businessInfo.setType(Long.parseLong("3"));
                businessInfo.setStatus(Long.parseLong("1"));
                businessInfo.setProType(Long.parseLong("1"));
                businessInfo.setCreateTime(DateUtils.getDateTime());
                businessInfo.setUpdateTime(DateUtils.getDateTime());
                businessInfoMapper.insertBusinessInfo(businessInfo);
            }

            /**
             * 轮播图
             **/
            for (MultipartFile dimg : dImg) {
                //上传
                pid = uploadImg(dimg);
                businessInfo = new BusinessInfo();
                businessInfo.setPicId(goodsInfo.getId());
                businessInfo.setDescribe("轮播图");
                businessInfo.setUrl(pid);
                businessInfo.setType(Long.parseLong("2"));
                businessInfo.setStatus(Long.parseLong("1"));
                businessInfo.setProType(Long.parseLong("1"));
                businessInfo.setCreateTime(DateUtils.getDateTime());
                businessInfo.setUpdateTime(DateUtils.getDateTime());
                businessInfoMapper.insertBusinessInfo(businessInfo);
            }
        }catch (Exception e){
            throw  new BusinessException("上传图片失败");
        }
        return 1;
    }



    /**
     * 修改商品
     * 
     * @param goodsInfo 商品
     * @return 结果
     */
    @Override
    public int updateGoodsInfo(GoodsInfo goodsInfo) {
        goodsInfo.setUpdateTime(DateUtils.getNowDate());

        //商品上架 必须存在（首图，轮播图，详情图）;最少为1张
        //
        if ("1".equals(goodsInfo.getState())) {
            BusinessInfo businessInfo = new BusinessInfo();
            businessInfo.setPicId(goodsInfo.getId());
            Map map = businessInfoMapper.queryImgGroup(businessInfo);
            if (Integer.parseInt(map.get("home").toString()) <= 0) {
                throw new BusinessException("缺少商品首页图");
            } else if (Integer.parseInt(map.get("lb").toString()) <= 0){
                throw new BusinessException("商品轮播图至少上传一张");
            } else if (Integer.parseInt(map.get("xq").toString()) <= 0){
                throw new BusinessException("商品详情图至少上传一张");
            }
        }
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    /**
     * 删除商品对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteGoodsInfoByIds(String ids)
    {
        return goodsInfoMapper.deleteGoodsInfoByIds(Convert.toStrArray(ids));
    }

    @Transactional
    @Override
    public int delGoodsImg(BusinessInfo businessInfo) {
        String newUrl = businessInfo.getUrl().replace(CustomConfig.getImgUrl(), "");
        businessInfo.setUrl(newUrl);

        //类型为轮播和详情那么必须要保留一张
        Map imgTypeCount = businessInfoMapper.queryImgGroup(businessInfo);
        if (MapUtils.isNotEmpty(imgTypeCount)) {
            //轮播
            if (Integer.parseInt(imgTypeCount.get("lb").toString()) == 1 && businessInfo.getType().intValue() == 2 ) {
                throw  new BusinessException("商品至少保留一张轮播图");
            }
            //详情
            if (Integer.parseInt(imgTypeCount.get("xq").toString()) == 1 && businessInfo.getType().intValue() == 3) {
                throw  new BusinessException("商品至少保留一张详情图");
            }
        }
        int i = businessInfoMapper.deleteBusinessInfoByName(businessInfo);
        if (i >= 1) {
            //删除图片服务器上的文件
            FastDFSClient.deleteFile(newUrl);
        } else {
            throw  new BusinessException("删除失败");
        }
        return i;
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int deleteGoodsInfoById(Long id)
    {
        return goodsInfoMapper.deleteGoodsInfoById(id);
    }


    /**
     * @Description 上传图片
     * @Param [imgFile]
     * @return java.lang.String
     **/
    public String uploadImg(MultipartFile imgFile) throws IOException {
        String clientName = imgFile.getOriginalFilename();
        if (StringUtils.isEmpty(clientName)) {
            return null;
        }
        String fileName = null;
        fileName = clientName.substring(clientName.indexOf("."), clientName.length());
        //临时文件
        File dfile = File.createTempFile("prefix", "_" + clientName);
        imgFile.transferTo(dfile);
        //上传至Fast的图片数据
        Map<String, String> metaList = new HashMap<String, String>();
        metaList.put("fileName", fileName);
        metaList.put("fileType", imgFile.getName());
        metaList.put("author", ShiroUtils.getSysUser().getLoginName());
        metaList.put("date", Utils.formateDate(2));//年月日 时分秒
        String fid = FastDFSClient.uploadFile(dfile, dfile.getName(), metaList);
        if (StringUtils.isEmpty(fid)) {
            throw  new BusinessException("首页图片上传失败,请重新上传");
        }
        return fid;
    }



}
